#include "RpcClient.h"
#include "myrpc\myrpc.pb.h"

namespace myrpc
{	

	myrpc::mythread::Atomic RpcClient::atomic_;
	void RpcClient::CallMethod(const google::protobuf::MethodDescriptor * method,
								google::protobuf::RpcController * controller,
								const google::protobuf::Message * request, 
								google::protobuf::Message * response,
								google::protobuf::Closure * done)
	{	
		assert("tcphandle_  must be initail");
		std::string name = method->name();
		const google::protobuf::ServiceDescriptor* servicedescriptor = method->service();
		myrpc::Request req;
		std::string data =  request->SerializeAsString();
		atomic_.Add();
		int id = atomic_.Get();
		req.set_id(id);
		req.set_data(data.c_str());
		req.set_method(name);
		req.set_service(servicedescriptor->name());
		std::string buf;
		req.SerializeToString(&buf);
		myrpc::Header header;
		header.set_len(buf.size());
		std::string len = header.SerializeAsString();
		buf = len + buf;
		requestlist_.insert(std::make_pair(id, RequetBodyPtr(new RequetBody(id, done, response))));
		tcphandle_->Send(buf  , buf.size());

	}

	int RpcClient::Connect(std::string ip , int port)
	{	

		tcphandle_->Setpackgereachhandle([=](std::shared_ptr<myrpc::mynet::ClientPackage> Package)
		{
			auto body = Package->body;
			auto id = body.id();
			RequetBodyPtr requetbody = requestlist_[id];
			requetbody->_response->ParseFromString(body.data());
			requetbody->_done->Run();
		});
		tcphandle_->Connect(ip , port);

		return 0;
	}
}


